<?php
/**
 * 管理员类
 * User: ws
 * Date: 2018/7/24
 * Time: 10:13
 */

namespace app\admin\controller;
use app\admin\model\AdminRole as RoleModel;

class Admin  extends Init
{
    function _initialize()
    {
        parent::_initialize();
        $this->model = model('admin_user');
    }



    function index(){
        if ($this->request->isAjax()) {
            $list = $this->model->with('role')->paginate(input('limit'))->toArray();
            return json($result = ['code'=>0,'msg'=>'获取成功','data'=>$list['data'],'count'=>$list['total']]);
        }
        return $this->fetch('list');
    }


    function add(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $username = $this->model->where('name',$data['name'])->find();
            if($username){
                return json(array('code'=>0,'msg'=>'添加失败，不能有相同的登录名'));
            }
            $data['pass'] = strtolower(md5($data['pass']));
            $relust = $this->model->add($data);
            if ($relust){
                return json(array('code'=>200,'msg'=>'添加成功'));
            }
            return json(array('code'=>0,'msg'=>'添加失败'));
        }

        $list = RoleModel::where('admin_role_id > 1')->paginate(20)->toArray();
        $this->assign('list', $list['data']);
        return $this->fetch('add');
    }



    function edit(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(empty($data['pass']) && empty($data['pass'])){
                unset($data['repass']);
                unset($data['pass']);
            }elseif($data['pass'] && !empty($data['repass'])){
                if($data['pass']!=$data['repass']){
                    return json(array('code'=>0,'msg'=>'两次密码不一样'));
                }
                $data['pass'] = strtolower(md5($data['pass']));
                unset($data['repass']);
            }else{
                return json(array('code'=>0,'msg'=>'请填写密码'));
            }

            $result = $this->model->edit($data);
            if($result){
                if ($_SESSION['think']['admin_user']['admin_user_id']==$data['admin_user_id']){
                    session(null);
                }
                return json(array('code'=>200,'msg'=>'修改成功'));
            }else{
                return json(array('code'=>0,'msg'=>'修改失败'));
            }
        }
        $list = $this->model->where('admin_user_id',input('id'))->find()->toArray();
        $role = RoleModel::where('admin_role_id > 1')->paginate(20)->toArray();
        return view('edit',array('list'=>$list,'role'=>$role['data']));
    }


    function del(){
        $result = $this->model->destroy(input('admin_user_id'));
        if($result){
            return json(array('code'=>200,'msg'=>'删除成功'));
        }else{
            return json(array('code'=>0,'msg'=>'删除失败'));
        }
    }

}